<template>
  <div class="param-config-page">
    <el-card shadow="hover" class="config-card">
      <!-- 配置页标题和工具栏 -->
      <div slot="header" class="page-header">
        <div class="header-left">
          <el-button
            @click="goBack"
            icon="el-icon-arrow-left"
            type="text"
            class="back-btn"
            >返回</el-button
          >
          <h2 class="page-title">工程质量检测参数配置</h2>
        </div>
        <div class="header-actions">
          <el-button
            type="primary"
            @click="saveConfig"
            :loading="saving"
            icon="el-icon-save"
          >
            保存配置
          </el-button>
          <el-button @click="showTemplateDialog" icon="el-icon-folder-opened">
            配置模板
          </el-button>
           <el-button 
            @click="showParamMappingDialog"
          >
            查看参数对照表
          </el-button>
          <el-button @click="showHistoryDialog" icon="el-icon-time">
            版本历史
          </el-button>
        </div>
      </div>

      <!-- 基础信息配置 -->
      <div class="base-info-section">
        <h3 class="section-title">基础信息</h3>
        <el-form
          ref="baseForm"
          :model="configForm"
          label-width="120px"
          class="base-info-form"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检测项目名称" prop="projectName" required>
                <el-input
                  v-model="configForm.projectName"
                  placeholder="如：钢筋母材及接头力学性能检测"
                  maxlength="50"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="执行标准" prop="standardCode" required>
                <el-input
                  v-model="configForm.standardCode"
                  placeholder="如：GB/T 228.1-2021"
                  maxlength="30"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目编码" prop="projectId" required>
                <el-input
                  v-model="configForm.projectId"
                  placeholder="如：REBAR001"
                  maxlength="20"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-refresh"
                    @click="generateProjectId"
                    title="自动生成"
                  ></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="项目描述">
            <el-input
              v-model="configForm.description"
              type="textarea"
              :rows="2"
              placeholder="请输入检测项目的详细描述..."
              maxlength="200"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <!-- 参数组配置区域 -->
      <div class="param-groups-section">
        <div class="section-header">
          <h3 class="section-title">参数组配置</h3>
          <div class="section-actions">
            <el-button
              type="primary"
              @click="addParamGroup"
              icon="el-icon-plus"
            >
              添加参数组
            </el-button>
            <el-button @click="showImportDialog" icon="el-icon-upload2">
              导入配置
            </el-button>
            <el-button @click="previewConfig" icon="el-icon-view">
              预览配置
            </el-button>
            <el-button @click="validateConfig" icon="el-icon-check">
              校验配置
            </el-button>
          </div>
        </div>

        <!-- 配置统计信息 -->
        <div class="config-stats">
          <el-tag type="info"
            >参数组: {{ configForm.paramGroups.length }}</el-tag
          >
          <el-tag type="info">总参数: {{ totalParams }}</el-tag>
          <el-tag type="info">基础参数: {{ baseParamsCount }}</el-tag>
          <el-tag type="info">计算参数: {{ calcParamsCount }}</el-tag>
        </div>

        <!-- 动态参数组列表 -->
        <draggable
          v-model="configForm.paramGroups"
          handle=".group-drag-handle"
          @end="onGroupDragEnd"
        >
          <div
            v-for="(group, groupIndex) in configForm.paramGroups"
            :key="group.groupId"
            class="param-group-card"
          >
            <!-- 参数组头部 -->
            <div class="group-header">
              <div class="group-header-left">
                <i class="el-icon-rank group-drag-handle"></i>
                <el-input
                  v-model="group.groupName"
                  placeholder="参数组名称（如：样品基础信息、拉伸试验）"
                  class="group-name-input"
                  maxlength="30"
                  show-word-limit
                ></el-input>
                <el-input-number
                  v-model="group.sortOrder"
                  :min="1"
                  :max="100"
                  size="mini"
                  controls-position="right"
                  class="sort-order-input"
                ></el-input-number>
              </div>
              <div class="group-header-actions">
                <el-tooltip content="嵌套组" placement="top">
                  <el-switch
                    v-model="group.isNested"
                    active-text="嵌套"
                    @change="handleNestedChange(groupIndex)"
                  ></el-switch>
                </el-tooltip>
                <el-tooltip content="动态表格（平行试验）" placement="top">
                  <el-switch
                    v-model="group.allowDynamicRows"
                    :disabled="group.isNested"
                    active-text="动态"
                  ></el-switch>
                </el-tooltip>
                <el-input
                  v-if="group.allowDynamicRows"
                  v-model.number="group.maxRows"
                  type="number"
                  placeholder="最大行数"
                  size="mini"
                  class="max-rows-input"
                  :min="1"
                  :max="20"
                ></el-input>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamGroup(groupIndex)"
                ></el-button>
              </div>
            </div>

            <!-- 嵌套组子组配置 -->
            <div v-if="group.isNested" class="nested-groups">
              <draggable
                v-model="group.childGroups"
                handle=".child-group-drag-handle"
                @end="onChildGroupDragEnd(groupIndex)"
              >
                <div
                  v-for="(childGroup, childIndex) in group.childGroups"
                  :key="childGroup.groupId"
                  class="child-group-card"
                >
                  <div class="child-group-header">
                    <i class="el-icon-rank child-group-drag-handle"></i>
                    <el-input
                      v-model="childGroup.groupName"
                      placeholder="子组名称（如：实测数据、理论计算）"
                      class="child-group-name-input"
                      maxlength="30"
                      show-word-limit
                    ></el-input>
                    <el-button
                      type="text"
                      icon="el-icon-plus"
                      size="mini"
                      @click="addParamItem(groupIndex, childIndex, true)"
                    >
                      添加参数
                    </el-button>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="removeChildGroup(groupIndex, childIndex)"
                    ></el-button>
                  </div>

                  <!-- 子组参数列表 -->
                  <param-item-table
                    :params="childGroup.paramItems"
                    :group-index="groupIndex"
                    :child-index="childIndex"
                    :is-nested="true"
                    @add-param="addParamItem"
                    @remove-param="removeParamItem"
                    @open-calc-dialog="openCalcRuleDialog"
                    @open-select-dialog="openSelectOptionsDialog"
                    @open-validate-dialog="openValidateRuleDialog"
                    @open-condition-dialog="openConditionShowDialog"
                  />
                </div>
              </draggable>
              <el-button
                type="text"
                icon="el-icon-plus"
                size="mini"
                @click="addChildGroup(groupIndex)"
                class="add-child-group-btn"
              >
                添加子组
              </el-button>
            </div>

            <!-- 非嵌套组参数配置 -->
            <div v-else class="normal-group-params">
              <div class="normal-group-header">
                <el-button
                  type="text"
                  icon="el-icon-plus"
                  size="mini"
                  @click="addParamItem(groupIndex, -1, false)"
                >
                  添加参数
                </el-button>
                <span class="param-count"
                  >共 {{ group.paramItems.length }} 个参数</span
                >
              </div>

              <param-item-table
                :params="group.paramItems"
                :group-index="groupIndex"
                :child-index="-1"
                :is-nested="false"
                @add-param="addParamItem"
                @remove-param="removeParamItem"
                @open-calc-dialog="openCalcRuleDialog"
                @open-select-dialog="openSelectOptionsDialog"
                @open-validate-dialog="openValidateRuleDialog"
                @open-condition-dialog="openConditionShowDialog"
              />
            </div>
          </div>
        </draggable>

        <!-- 空状态提示 -->
        <div v-if="configForm.paramGroups.length === 0" class="empty-state">
          <i class="el-icon-files empty-icon"></i>
          <p>暂无参数组，点击上方按钮添加参数组</p>
          <el-button type="primary" @click="addParamGroup" icon="el-icon-plus">
            添加第一个参数组
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 所有弹窗组件 -->
    <select-options-dialog
      :visible="selectOptionsDialogVisible"
      :options="currentSelectOptions"
      @update:visible="selectOptionsDialogVisible = $event"
      @save="saveSelectOptions"
      @add-option="addSelectOption"
      @remove-option="removeSelectOption"
    />

    <validate-rule-dialog
      :visible="validateDialogVisible"
      :rule="currentValidateRule"
      :param="currentParam"
      @update:visible="validateDialogVisible = $event"
      @save="handleValidateRuleSave"
    />

    <condition-rule-dialog
      :visible="conditionDialogVisible"
      :rule="currentConditionRule"
      :all-base-params="getAllBaseParams()"
      @update:visible="conditionDialogVisible = $event"
      @save="handleConditionRuleSave"
    />

    <preview-dialog
      :visible="previewDialogVisible"
      :json="previewJson"
      @update:visible="previewDialogVisible = $event"
    />

    <import-dialog
      :visible="importDialogVisible"
      :form="importForm"
      @update:visible="importDialogVisible = $event"
      @import="handleImportConfig"
    />

    <calc-rule-dialog
      :visible="calcRuleDialogVisible"
      :rule="currentCalcRule"
      :base-params="currentGroupBaseParams"
      :has-multi-measure-params="hasMultiMeasureParams"
      :multi-measure-deps="multiMeasureDeps"
      :validate-loading="validateLoading"
      :validate-result="validateResult"
      :validate-success="validateSuccess"
      @update:visible="calcRuleDialogVisible = $event"
      @dependencies-change="handleCalcDependenciesChange"
      @validate="handleValidateCalcExpression"
      @save="handleCalcRuleSave"
    />

    <template-dialog
      :visible="templateDialogVisible"
      :templates="templateConfigs"
      @update:visible="templateDialogVisible = $event"
      @apply="applyTemplate"
    />

    <history-dialog
      :visible="historyDialogVisible"
      :history="configHistory"
      @update:visible="historyDialogVisible = $event"
      @restore="restoreConfigVersion"
    />

    <!-- 全局加载遮罩 -->
    <div v-if="globalLoading" class="global-loading">
      <div class="loading-content">
        <i class="el-icon-loading"></i>
        <p>加载中...</p>
      </div>
    </div>

     <!-- 参数对照表弹框 -->
    <el-dialog
      title="参数对照表"
      :visible.sync="mappingDialogVisible"
      width="90%"
      top="5vh"
      custom-class="param-mapping-dialog"
      :close-on-click-modal="false"
    >
      <param-mapping 
        ref="paramMapping" 
        :project-config="mappingJson" 
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="mappingDialogVisible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="handleExportMapping('markdown')"
        >
          导出Markdown
        </el-button>
        <el-button 
          type="success" 
          @click="handleExportMapping('csv')"
        >
          导出CSV
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { generateId, deepClone } from '@/utils/tools'
import { Message, MessageBox } from 'element-ui'
import ParamItemTable from '@/components/ParamItemTable.vue'
import SelectOptionsDialog from '@/components/dialogs/SelectOptionsDialog.vue'
import ValidateRuleDialog from '@/components/dialogs/ValidateRuleDialog.vue'
import ConditionRuleDialog from '@/components/dialogs/ConditionRuleDialog.vue'
import PreviewDialog from '@/components/dialogs/PreviewDialog.vue'
import ImportDialog from '@/components/dialogs/ImportDialog.vue'
import CalcRuleDialog from '@/components/dialogs/CalcRuleDialog.vue'
import TemplateDialog from '@/components/dialogs/TemplateDialog.vue'
import HistoryDialog from '@/components/dialogs/HistoryDialog.vue'
import FormulaCalculator from '@/utils/FormulaCalculator'
import ParamMapping from '@/components/ParamMapping'

export default {
  name: 'ParamConfigPage',
  components: {
    draggable,
    ParamItemTable,
    SelectOptionsDialog,
    ValidateRuleDialog,
    ConditionRuleDialog,
    PreviewDialog,
    ImportDialog,
    CalcRuleDialog,
    TemplateDialog,
    HistoryDialog,
    ParamMapping
  },
  data() {
    return {
      // 配置表单数据
      configForm: {
        projectId: '',
        projectName: '',
        standardCode: '',
        description: '',
        paramGroups: []
      },
      mappingDialogVisible: false,
      mappingJson: {},
      // 加载状态
      globalLoading: false,
      saving: false,
      tableLoading: false,
      validateLoading: false,

      // 弹窗控制
      selectOptionsDialogVisible: false,
      validateDialogVisible: false,
      conditionDialogVisible: false,
      previewDialogVisible: false,
      importDialogVisible: false,
      calcRuleDialogVisible: false,
      templateDialogVisible: false,
      historyDialogVisible: false,

      // 当前操作数据
      currentParam: null,
      currentSelectParam: null,
      currentSelectOptions: [],
      currentValidateRule: {},
      currentConditionRule: {},
      currentCalcParam: null,
      currentCalcRule: {},
      currentGroupBaseParams: [],
      currentGroupInfo: {
        groupIndex: -1,
        childIndex: -1,
        isNested: false
      },

      // 导入配置
      importForm: {
        jsonStr: '',
        coverType: 'cover'
      },

      // 计算规则校验
      validateResult: '',
      validateSuccess: false,
      hasMultiMeasureParams: false,
      multiMeasureDeps: [],

      // 配置模板
      templateConfigs: {
        rebarTensile: {
          projectName: '钢筋拉伸试验',
          standardCode: 'GB/T 228.1-2021',
          description: '钢筋母材及焊接接头拉伸性能检测',
          paramGroups: [
            {
              groupName: '样品信息',
              sortOrder: 1,
              paramItems: [
                {
                  paramName: '样品编号',
                  paramCode: 'sample_no',
                  dataType: 'text',
                  required: true,
                  placeholder: '请输入样品编号',
                  columnWidth: 120
                },
                {
                  paramName: '钢筋规格',
                  paramCode: 'rebar_spec',
                  dataType: 'text',
                  placeholder: '如：HRB400 Φ25',
                  columnWidth: 120
                },
                {
                  paramName: '公称直径',
                  paramCode: 'nominal_diameter',
                  dataType: 'number',
                  unit: 'mm',
                  precision: 1,
                  columnWidth: 100
                }
              ]
            },
            {
              groupName: '拉伸试验',
              isNested: true,
              sortOrder: 2,
              childGroups: [
                {
                  groupName: '实测数据',
                  paramItems: [
                    {
                      paramName: '屈服荷载',
                      paramCode: 'yield_load',
                      dataType: 'number',
                      unit: 'kN',
                      precision: 2,
                      columnWidth: 100,
                      isMultiMeasure: true,
                      multiMeasureCount: 3
                    },
                    {
                      paramName: '最大荷载',
                      paramCode: 'max_load',
                      dataType: 'number',
                      unit: 'kN',
                      precision: 2,
                      columnWidth: 100,
                      isMultiMeasure: true,
                      multiMeasureCount: 3
                    }
                  ]
                },
                {
                  groupName: '计算结果',
                  paramItems: [
                    {
                      paramName: '屈服强度',
                      paramCode: 'yield_strength',
                      dataType: 'number',
                      paramType: 'calculation',
                      unit: 'MPa',
                      precision: 1,
                      dependencies: ['yield_load', 'nominal_diameter'],
                      calculationExpr:
                        'ROUND(yield_load * 1000 / (3.1416 * POW(nominal_diameter/2, 2)), 1)',
                      columnWidth: 100
                    },
                    {
                      paramName: '抗拉强度',
                      paramCode: 'tensile_strength',
                      dataType: 'number',
                      paramType: 'calculation',
                      unit: 'MPa',
                      precision: 1,
                      dependencies: ['max_load', 'nominal_diameter'],
                      calculationExpr:
                        'ROUND(max_load * 1000 / (3.1416 * POW(nominal_diameter/2, 2)), 1)',
                      columnWidth: 100
                    }
                  ]
                }
              ]
            }
          ]
        },
        concreteCompressive: {
          projectName: '混凝土抗压强度检测',
          standardCode: 'GB/T 50081-2019',
          description: '混凝土立方体试块抗压强度检测',
          paramGroups: [
            {
              groupName: '试件信息',
              sortOrder: 1,
              paramItems: [
                {
                  paramName: '试件编号',
                  paramCode: 'specimen_no',
                  dataType: 'text',
                  required: true,
                  columnWidth: 120
                },
                {
                  paramName: '试件尺寸',
                  paramCode: 'specimen_size',
                  dataType: 'text',
                  columnWidth: 100
                },
                {
                  paramName: '养护条件',
                  paramCode: 'curing_condition',
                  dataType: 'select',
                  options: [
                    { label: '标准养护', value: 'standard' },
                    { label: '同条件养护', value: 'same_condition' }
                  ],
                  columnWidth: 120
                }
              ]
            },
            {
              groupName: '抗压试验',
              allowDynamicRows: true,
              maxRows: 6,
              sortOrder: 2,
              paramItems: [
                {
                  paramName: '破坏荷载',
                  paramCode: 'failure_load',
                  dataType: 'number',
                  unit: 'kN',
                  precision: 2,
                  columnWidth: 100
                },
                {
                  paramName: '抗压强度',
                  paramCode: 'compressive_strength',
                  dataType: 'number',
                  paramType: 'calculation',
                  unit: 'MPa',
                  precision: 1,
                  dependencies: ['failure_load', 'specimen_size'],
                  calculationExpr:
                    'ROUND(failure_load * 1000 / (150 * 150), 1)',
                  columnWidth: 100
                }
              ]
            }
          ]
        },
        testFIles: {
          projectName: '测试数据1',
          standardCode: 'GB/T 50081-2019',
          description: '测试1',
          paramGroups: [
            {
              groupId: 'GRPVENMTd',
              groupName: '参数组1',
              isNested: false,
              allowDynamicRows: false,
              maxRows: 3,
              sortOrder: 2,
              childGroups: [],
              paramItems: [
                {
                  paramId: 'PARAMkpglYW5V',
                  paramName: '新参数1',
                  paramCode: 'a_ui8b',
                  dataType: 'number',
                  paramType: 'base',
                  unit: '',
                  required: false,
                  calculationExpr: '',
                  dependencies: [],
                  options: [],
                  validateRule: {},
                  conditionShow: {},
                  precision: 1,
                  columnWidth: 120,
                  placeholder: '',
                  isMultiMeasure: false,
                  multiMeasureCount: 1,
                  sortOrder: 1
                },
                {
                  paramId: 'PARAMLQoGTiTn',
                  paramName: '新参数2',
                  paramCode: 'a_udfi',
                  dataType: 'text',
                  paramType: 'base',
                  unit: '',
                  required: false,
                  calculationExpr: '',
                  dependencies: [],
                  options: [],
                  validateRule: {},
                  conditionShow: {},
                  precision: 1,
                  columnWidth: 120,
                  placeholder: '',
                  isMultiMeasure: false,
                  multiMeasureCount: 1,
                  sortOrder: 2
                },
                {
                  paramId: 'PARAMOOO1UEZb',
                  paramName: '新参数',
                  paramCode: 'a_u9bh',
                  dataType: 'number',
                  paramType: 'calculation',
                  unit: 'kp',
                  required: false,
                  calculationExpr: 'ROUND(a_ui8b * 1.0, 2)',
                  dependencies: ['a_ui8b'],
                  options: [],
                  validateRule: {
                    min: 1,
                    max: 10000,
                    required: true,
                    requiredMsg: '此字段为必填项',
                    rangeMsg: '压力值在1-10000KMG'
                  },
                  conditionShow: {},
                  precision: 1,
                  columnWidth: 120,
                  placeholder: '',
                  isMultiMeasure: false,
                  multiMeasureCount: 1,
                  sortOrder: 3
                }
              ]
            },
            {
              groupId: 'GRP0yBIZl',
              groupName: '参数组2',
              isNested: true,
              allowDynamicRows: false,
              maxRows: 3,
              sortOrder: 2,
              childGroups: [
                {
                  groupId: 'GRP0yBIZl_CH66Sl',
                  groupName: '子组1',
                  paramItems: [
                    {
                      paramId: 'PARAM507QIVU8',
                      paramName: '新参数3',
                      paramCode: 'a_xqgx',
                      dataType: 'text',
                      paramType: 'base',
                      unit: '',
                      required: false,
                      calculationExpr: '',
                      dependencies: [],
                      options: [],
                      validateRule: {},
                      conditionShow: {},
                      precision: 1,
                      columnWidth: 120,
                      placeholder: '',
                      isMultiMeasure: false,
                      multiMeasureCount: 1,
                      sortOrder: 1
                    },
                    {
                      paramId: 'PARAMd8Tp8zYZ',
                      paramName: '新参数4',
                      paramCode: 'a_390n',
                      dataType: 'text',
                      paramType: 'base',
                      unit: '',
                      required: false,
                      calculationExpr: '',
                      dependencies: [],
                      options: [],
                      validateRule: {},
                      conditionShow: {},
                      precision: 1,
                      columnWidth: 120,
                      placeholder: '',
                      isMultiMeasure: false,
                      multiMeasureCount: 1,
                      sortOrder: 2
                    }
                  ]
                },
                {
                  groupId: 'GRP0yBIZl_CHmkfd',
                  groupName: '子组2',
                  paramItems: [
                    {
                      paramId: 'PARAM5qpzSRdM',
                      paramName: '新参数5',
                      paramCode: 'a_4t2t',
                      dataType: 'number',
                      paramType: 'base',
                      unit: '',
                      required: false,
                      calculationExpr: '',
                      dependencies: [],
                      options: [],
                      validateRule: {},
                      conditionShow: {},
                      precision: 1,
                      columnWidth: 120,
                      placeholder: '',
                      isMultiMeasure: false,
                      multiMeasureCount: 1,
                      sortOrder: 1
                    },
                    {
                      paramId: 'PARAMo5jiZRGW',
                      paramName: '新参数6',
                      paramCode: 'a_sc4j',
                      dataType: 'number',
                      paramType: 'calculation',
                      unit: '',
                      required: false,
                      calculationExpr: 'ROUND(a_u9bh * 1.0 + a_4t2t, 2)',
                      dependencies: ['a_u9bh', 'a_4t2t'],
                      options: [],
                      validateRule: {},
                      conditionShow: {},
                      precision: 1,
                      columnWidth: 120,
                      placeholder: '',
                      isMultiMeasure: false,
                      multiMeasureCount: 1,
                      sortOrder: 2
                    }
                  ]
                }
              ],
              paramItems: []
            },
            {
              groupId: 'GRPV25tsl',
              groupName: '参数组3',
              isNested: false,
              allowDynamicRows: true,
              maxRows: 3,
              sortOrder: 3,
              childGroups: [],
              paramItems: [
                {
                  paramId: 'PARAMHPXzBu3J',
                  paramName: '新参数7',
                  paramCode: 'a_ddoi',
                  dataType: 'number',
                  paramType: 'base',
                  unit: '',
                  required: false,
                  calculationExpr: '',
                  dependencies: [],
                  options: [],
                  validateRule: {},
                  conditionShow: {},
                  precision: 1,
                  columnWidth: 180,
                  placeholder: '',
                  isMultiMeasure: true,
                  multiMeasureCount: 3,
                  sortOrder: 1
                },
                {
                  paramId: 'PARAMPTn8RUJC',
                  paramName: '新参数8',
                  paramCode: 'a_01mv',
                  dataType: 'number',
                  paramType: 'base',
                  unit: '',
                  required: false,
                  calculationExpr: '',
                  dependencies: [],
                  options: [],
                  validateRule: {},
                  conditionShow: {},
                  precision: 1,
                  columnWidth: 180,
                  placeholder: '',
                  isMultiMeasure: true,
                  multiMeasureCount: 3,
                  sortOrder: 2
                },
                {
                  paramId: 'PARAMTrGiCRml',
                  paramName: '新参数9',
                  paramCode: 'a_lomi',
                  dataType: 'number',
                  paramType: 'calculation',
                  unit: '',
                  required: false,
                  calculationExpr:
                    'ROUND(AVG(a_ddoi[0].value, a_ddoi[1].value, a_ddoi[2].value) + AVG(a_01mv[0].value, a_01mv[1].value, a_01mv[2].value), 2)',
                  dependencies: ['a_ddoi', 'a_01mv', 'a_ui8b'],
                  options: [],
                  validateRule: {},
                  conditionShow: {},
                  precision: 1,
                  columnWidth: 120,
                  placeholder: '',
                  isMultiMeasure: false,
                  multiMeasureCount: 1,
                  sortOrder: 3
                }
              ]
            }
          ]
        },
        yylTemplate:{
  "projectId": "PROJ489793851",
  "projectName": "预应力混凝土用钢绞线检测",
  "standardCode": "GB/T 220.1-2021",
  "description": "预应力混凝土用钢绞线检测",
  "paramGroups": [
    {
      "groupId": "GRPDqfjTF",
      "groupName": "检测内容",
      "isNested": false,
      "allowDynamicRows": false,
      "maxRows": 3,
      "sortOrder": 1,
      "childGroups": [],
      "paramItems": [
        {
          "paramId": "PARAME3PzL8o6",
          "paramName": "直 径(mm)",
          "paramCode": "yhqrvp",
          "dataType": "number",
          "paramType": "base",
          "unit": "mm",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "请输入",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 1
        },
        {
          "paramId": "PARAMqac7WdMQ",
          "paramName": "面 积(mm2)",
          "paramCode": "yhmaqh",
          "dataType": "number",
          "paramType": "base",
          "unit": "mm²",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "请输入",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 2
        },
        {
          "paramId": "PARAMyJH5eQF1",
          "paramName": "整根钢绞线的最大力(kN)",
          "paramCode": "yh05bb",
          "dataType": "number",
          "paramType": "base",
          "unit": "kN",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "请输入",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 3
        },
        {
          "paramId": "PARAME9HzWdnQ",
          "paramName": "最大力总伸长率(%)",
          "paramCode": "yhjza2",
          "dataType": "number",
          "paramType": "base",
          "unit": "%",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 4
        },
        {
          "paramId": "PARAM60urGae8",
          "paramName": "试件实测长度（mm）",
          "paramCode": "yhm96h",
          "dataType": "number",
          "paramType": "base",
          "unit": "mm",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 5
        },
        {
          "paramId": "PARAM9Y3Ymr17",
          "paramName": "试件实测总重量（㎏）",
          "paramCode": "yh96u6",
          "dataType": "number",
          "paramType": "base",
          "unit": "kg",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 6
        },
        {
          "paramId": "PARAMz4a49gg6",
          "paramName": "理论重量（㎏/m）",
          "paramCode": "yh67e1",
          "dataType": "number",
          "paramType": "base",
          "unit": "kg",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 7
        },
        {
          "paramId": "PARAMXrPLB4VZ",
          "paramName": "重量偏差（％）",
          "paramCode": "yh8z5f",
          "dataType": "number",
          "paramType": "base",
          "unit": "%",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 8
        },
        {
          "paramId": "PARAM6lT5RYW6",
          "paramName": "标 距(mm)",
          "paramCode": "yhdc0d",
          "dataType": "number",
          "paramType": "base",
          "unit": "mm",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 9
        }
      ]
    },
    {
      "groupId": "GRPEHTBPB",
      "groupName": "平均值及结论",
      "isNested": false,
      "allowDynamicRows": false,
      "maxRows": 3,
      "sortOrder": 2,
      "childGroups": [],
      "paramItems": [
        {
          "paramId": "PARAMO2d8PUKL",
          "paramName": "直 径(mm)",
          "paramCode": "yhp9uo",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "mm",
          "required": false,
          "calculationExpr": "ROUND(AVG(yhqrvp[0].value, yhqrvp[1].value, yhqrvp[2].value), 2)",
          "dependencies": [
            "yhqrvp"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 1
        },
        {
          "paramId": "PARAM3shI9K8z",
          "paramName": "面 积(mm2)",
          "paramCode": "yhiwuz",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "mm²",
          "required": false,
          "calculationExpr": "ROUND(AVG(yhmaqh[0].value, yhmaqh[1].value, yhmaqh[2].value), 2)",
          "dependencies": [
            "yhmaqh"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 2
        },
        {
          "paramId": "PARAMKXwQanEN",
          "paramName": "标 距(mm)",
          "paramCode": "yho6er",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "mm",
          "required": false,
          "calculationExpr": "ROUND(AVG(yhdc0d[0].value, yhdc0d[1].value, yhdc0d[2].value), 2)",
          "dependencies": [
            "yhdc0d"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 3
        },
        {
          "paramId": "PARAMICPVOhke",
          "paramName": "整根钢绞线的最大力(kN)",
          "paramCode": "yhxqr9",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "kN",
          "required": false,
          "calculationExpr": "ROUND(AVG(yh05bb[0].value, yh05bb[1].value, yh05bb[2].value), 2)",
          "dependencies": [
            "yh05bb"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 4
        },
        {
          "paramId": "PARAMt9YjbiPX",
          "paramName": "最大力总伸长率(%)",
          "paramCode": "yhdma3",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "%",
          "required": false,
          "calculationExpr": "ROUND(AVG(yhjza2[0].value, yhjza2[1].value, yhjza2[2].value), 2)",
          "dependencies": [
            "yhjza2"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 5
        },
        {
          "paramId": "PARAM8IDV9YDK",
          "paramName": "试件实测长度（mm）",
          "paramCode": "yhhrci",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "mm",
          "required": false,
          "calculationExpr": "ROUND(AVG(yhm96h[0].value, yhm96h[1].value, yhm96h[2].value), 2)",
          "dependencies": [
            "yhm96h"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 6
        },
        {
          "paramId": "PARAMG1VjzLjF",
          "paramName": "试件实测总重量（㎏）",
          "paramCode": "yhmeua",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "kg",
          "required": false,
          "calculationExpr": "ROUND(AVG(yh96u6[0].value, yh96u6[1].value, yh96u6[2].value), 2)",
          "dependencies": [
            "yh96u6"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 7
        },
        {
          "paramId": "PARAM7viIRyHQ",
          "paramName": "理论重量（㎏/m）",
          "paramCode": "yhci3n",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "kg",
          "required": false,
          "calculationExpr": "ROUND(AVG(yh67e1[0].value, yh67e1[1].value, yh67e1[2].value), 2)",
          "dependencies": [
            "yh67e1"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 8
        },
        {
          "paramId": "PARAM7W5iYZuK",
          "paramName": "重量偏差（％）",
          "paramCode": "yhb5tt",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "%",
          "required": false,
          "calculationExpr": "ROUND(AVG(yh8z5f[0].value, yh8z5f[1].value, yh8z5f[2].value), 2)",
          "dependencies": [
            "yh8z5f"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 120,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 9
        },
        {
          "paramId": "PARAMMQdLg6CY",
          "paramName": "直径结论",
          "paramCode": "yhc4fs",
          "dataType": "text",
          "paramType": "calculation",
          "unit": "",
          "required": false,
          "calculationExpr": "IF(GT(yhp9uo , 15), \"合格\", \"不合格\")",
          "dependencies": [
            "yhp9uo"
          ],
          "options": [
            {
              "label": "合格",
              "value": "1"
            },
            {
              "label": "不合格",
              "value": "2"
            }
          ],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 120,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 10
        }
      ]
    },
    {
      "groupId": "GRPZA8JBz",
      "groupName": "备注",
      "isNested": false,
      "allowDynamicRows": false,
      "maxRows": 3,
      "sortOrder": 3,
      "childGroups": [],
      "paramItems": [
        {
          "paramId": "PARAMGwHrib7G",
          "paramName": "备注",
          "paramCode": "yhq60e",
          "dataType": "text",
          "paramType": "base",
          "unit": "",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 150,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 1
        }
      ]
    }
  ]
}
      },

      // 配置版本历史
      configHistory: [],
      currentVersion: 0,

      // 公式计算器
      formulaCalculator: new FormulaCalculator(),

      // 预览数据
      previewJson: ''
    }
  },
  computed: {
    // 总参数数量
    totalParams() {
      let count = 0
      this.configForm.paramGroups.forEach((group) => {
        if (group.isNested) {
          group.childGroups.forEach((childGroup) => {
            count += childGroup.paramItems.length
          })
        } else {
          count += group.paramItems.length
        }
      })
      return count
    },

    // 基础参数数量
    baseParamsCount() {
      return this.countParamsByType('base')
    },

    // 计算参数数量
    calcParamsCount() {
      return this.countParamsByType('calculation')
    }
  },
  created() {
    this.loadConfig()
    this.saveConfigVersion() // 保存初始版本
  },
  methods: {
    // 加载配置
    loadConfig() {
      // 模拟从后端加载数据
      this.globalLoading = true
      setTimeout(() => {
        // 实际项目中这里应该是API调用
        const savedConfig = localStorage.getItem('detectionConfig')
        if (savedConfig) {
          try {
            this.configForm = JSON.parse(savedConfig)
          } catch (e) {
            console.error('加载配置失败:', e)
          }
        }
        this.globalLoading = false
      }, 500)
    },

    // 返回上一页
    goBack() {
      this.$confirm('确定要离开吗？未保存的更改将会丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$router.go(-1)
        })
        .catch(() => {})
    },

    // 生成项目编码
    generateProjectId() {
      const prefix = 'PROJ'
      const timestamp = new Date().getTime().toString().slice(-6)
      const random = Math.floor(Math.random() * 1000)
        .toString()
        .padStart(3, '0')
      this.configForm.projectId = `${prefix}${timestamp}${random}`
    },

    // 添加参数组
    addParamGroup() {
      const newGroup = {
        groupId: `GRP${generateId(6)}`,
        groupName: `参数组${this.configForm.paramGroups.length + 1}`,
        isNested: false,
        allowDynamicRows: false,
        maxRows: 3,
        sortOrder: this.configForm.paramGroups.length + 1,
        childGroups: [],
        paramItems: []
      }
      this.configForm.paramGroups.push(newGroup)
    },

    // 移除参数组
    removeParamGroup(index) {
      MessageBox.confirm(
        '确定要删除该参数组吗？组内所有参数将一并删除。',
        '警告',
        {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消'
        }
      )
        .then(() => {
          this.configForm.paramGroups.splice(index, 1)
          Message.success('参数组删除成功')
        })
        .catch(() => {})
    },

    // 嵌套组切换处理
    handleNestedChange(groupIndex) {
      const group = this.configForm.paramGroups[groupIndex]
      if (group.isNested) {
        group.allowDynamicRows = false
        if (group.childGroups.length === 0) {
          this.addChildGroup(groupIndex)
        }
      }
    },

    // 添加子组
    addChildGroup(groupIndex) {
      const group = this.configForm.paramGroups[groupIndex]
      const newChildGroup = {
        groupId: `${group.groupId}_CH${generateId(4)}`,
        groupName: `子组${group.childGroups.length + 1}`,
        paramItems: []
      }
      group.childGroups.push(newChildGroup)
    },

    // 移除子组
    removeChildGroup(groupIndex, childIndex) {
      MessageBox.confirm(
        '确定要删除该子组吗？组内所有参数将一并删除。',
        '警告',
        {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消'
        }
      )
        .then(() => {
          this.configForm.paramGroups[groupIndex].childGroups.splice(
            childIndex,
            1
          )
          Message.success('子组删除成功')
        })
        .catch(() => {})
    },

    // 添加参数项
    addParamItem(groupIndex, childIndex, isNested) {
      const newParam = {
        paramId: `PARAM${generateId(8)}`,
        paramName: '新参数',
        paramCode: this.generateParamCode('yh'),
        dataType: 'text',
        paramType: 'base',
        unit: '',
        required: false,
        calculationExpr: '',
        dependencies: [],
        options: [],
        validateRule: {},
        conditionShow: {},
        precision: 1,
        columnWidth: 120,
        placeholder: '',
        isMultiMeasure: false,
        multiMeasureCount: 1,
        sortOrder: this.getNextSortOrder(groupIndex, childIndex, isNested)
      }

      if (isNested) {
        this.configForm.paramGroups[groupIndex].childGroups[
          childIndex
        ].paramItems.push(newParam)
      } else {
        this.configForm.paramGroups[groupIndex].paramItems.push(newParam)
      }
    },

    // 生成参数编码
    generateParamCode(paramName) {
      // 简化的拼音转换逻辑
      const pinyinMap = {
        强度: 'qd',
        荷载: 'hz',
        长度: 'cd',
        宽度: 'kd',
        厚度: 'hd',
        重量: 'zl',
        温度: 'wd',
        湿度: 'sd',
        编号: 'bh',
        规格: 'gg',
        直径: 'zj',
        面积: 'mj'
      }

      let code = ''
      for (const [key, value] of Object.entries(pinyinMap)) {
        if (paramName.includes(key)) {
          code += value
          paramName = paramName.replace(key, '')
        }
      }

      // 剩余字符处理
      if (paramName.length > 0) {
        code += paramName.slice(0, 2)
      }

      const randomSuffix = Math.random().toString(36).substr(2, 4)
      return `${code || 'param'}${randomSuffix}`.toLowerCase()
    },

    // 获取下一个排序序号
    getNextSortOrder(groupIndex, childIndex, isNested) {
      let paramItems = []
      if (isNested) {
        paramItems =
          this.configForm.paramGroups[groupIndex].childGroups[childIndex]
            .paramItems
      } else {
        paramItems = this.configForm.paramGroups[groupIndex].paramItems
      }
      return paramItems.length + 1
    },

    // 移除参数项
    removeParamItem(groupIndex, childIndex, isNested, paramIndex) {
      MessageBox.confirm('确定要删除该参数吗？此操作不可恢复。', '警告', {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          if (isNested) {
            this.configForm.paramGroups[groupIndex].childGroups[
              childIndex
            ].paramItems.splice(paramIndex, 1)
          } else {
            this.configForm.paramGroups[groupIndex].paramItems.splice(
              paramIndex,
              1
            )
          }
          Message.success('参数删除成功')
        })
        .catch(() => {})
    },

    // 参数组拖拽结束
    onGroupDragEnd() {
      // 更新排序序号
      this.configForm.paramGroups.forEach((group, index) => {
        group.sortOrder = index + 1
      })
    },

    // 子组拖拽结束
    onChildGroupDragEnd() {
      // 可以在这里添加子组排序逻辑
    },

    // 统计参数数量
    countParamsByType(paramType) {
      let count = 0
      this.traverseAllParams((param) => {
        if (param.paramType === paramType) count++
      })
      return count
    },

    // 遍历所有参数
    traverseAllParams(callback) {
      this.configForm.paramGroups.forEach((group) => {
        if (group.isNested) {
          group.childGroups.forEach((childGroup) => {
            (childGroup.paramItems || []).forEach(callback)
          })
        } else {
          (group.paramItems || []).forEach(callback)
        }
      })
    },

    // 获取所有基础参数（用于计算参数依赖选择）
        getAllBaseParams() {
      const allParams = []

      this.configForm.paramGroups.forEach((group) => {
        const pushParam = (param, groupPath) => {
          allParams.push({
            ...param,
            groupPath
          })
        }

        if (group.isNested) {
          group.childGroups.forEach((childGroup) => {
            childGroup.paramItems.forEach((param) => {
              pushParam(param, `${group.groupName} > ${childGroup.groupName}`)
            })
          })
        } else {
          group.paramItems.forEach((param) => {
            pushParam(param, group.groupName)
          })
        }
      })

      return allParams
    },

    // 获取当前组的基础参数（保持原有逻辑，但仅用于特定场景）
    getBaseParamsOfCurrentGroup() {
      const { groupIndex, childIndex, isNested } = this.currentGroupInfo
      if (groupIndex === -1) return []

      const group = this.configForm.paramGroups[groupIndex]
      let paramItems = []

      if (isNested) {
        const childGroup = group.childGroups[childIndex]
        paramItems = childGroup.paramItems || []
      } else {
        paramItems = group.paramItems || []
      }

      return paramItems.filter((p) => p.paramType === 'base')
    },

    // 打开下拉选项配置弹窗
    openSelectOptionsDialog(param) {
      this.currentSelectParam = param
      this.currentSelectOptions = deepClone(param.options || [])
      this.selectOptionsDialogVisible = true
    },

    // 添加下拉选项
    addSelectOption() {
      this.currentSelectOptions.push({
        label: `选项${this.currentSelectOptions.length + 1}`,
        value: `value${this.currentSelectOptions.length + 1}`
      })
    },

    // 移除下拉选项
    removeSelectOption(index) {
      this.currentSelectOptions.splice(index, 1)
    },

    // 保存下拉选项配置
    saveSelectOptions() {
      if (this.currentSelectParam) {
        this.currentSelectParam.options = this.currentSelectOptions
        Message.success('下拉选项配置成功')
      }
      this.selectOptionsDialogVisible = false
    },

    // 打开校验规则配置弹窗
    openValidateRuleDialog(param) {
      this.currentParam = param
      // 注意：这里我们使用param.validateRule，如果不存在则使用空对象，但结构要与对话框的rule一致
      this.currentValidateRule = { ...(param.validateRule || {}) }
      this.validateDialogVisible = true
    },

    // 处理保存校验规则
    handleValidateRuleSave(updatedRule) {
      // 更新当前参数的validateRule
      if (this.currentParam) {
        // 注意：这里我们直接给currentParam.validateRule赋值，因为currentParam是引用，所以会更新到configForm中
        this.currentParam.validateRule = updatedRule
      }
      this.validateDialogVisible = false
      this.$message.success('校验规则配置成功')
    },
    // 打开条件显示规则配置弹窗
    openConditionShowDialog(param) {
      this.currentParam = param
      // 确保使用深拷贝，避免引用问题
      this.currentConditionRule = deepClone(param.conditionShow || {})
      this.conditionDialogVisible = true
    },

    // 处理条件显示规则保存
    handleConditionRuleSave(updatedRule) {
      if (this.currentParam) {
        // 直接更新当前参数的条件显示规则
        this.currentParam.conditionShow = updatedRule

        // 触发响应式更新
        this.$forceUpdate()

        this.$message.success('条件显示规则配置成功')
      } else {
        this.$message.error('保存失败：未找到对应的参数')
      }
    },

    // 打开计算规则配置弹窗
    openCalcRuleDialog(param, groupIndex, childIndex, isNested) {
      this.currentCalcParam = param
      this.currentGroupInfo = { groupIndex, childIndex, isNested }

      // 使用 JSON 方法进行深拷贝
      this.currentCalcRule = JSON.parse(
        JSON.stringify({
          dependencies: param.dependencies || [],
          calculationExpr: param.calculationExpr || ''
        })
      )

      // 修改这里：使用所有基础参数，而不仅仅是当前组的
      this.currentGroupBaseParams = this.getAllBaseParams()
      this.identifyMultiMeasureDeps()
      this.calcRuleDialogVisible = true
    },

    // 识别多测次参数
    identifyMultiMeasureDeps() {
      const { dependencies } = this.currentCalcRule
      if (!dependencies.length) {
        this.hasMultiMeasureParams = false
        this.multiMeasureDeps = []
        return
      }

      // 从所有基础参数中筛选多测次依赖参数
      const multiDeps = this.currentGroupBaseParams.filter(
        (param) =>
          dependencies.includes(param.paramCode) &&
          param.isMultiMeasure &&
          param.multiMeasureCount > 1
      )

      this.hasMultiMeasureParams = multiDeps.length > 0
      this.multiMeasureDeps = multiDeps
    },

    // 处理计算规则依赖参数变更
    handleCalcDependenciesChange(updatedDependencies) {
      // 更新本地规则
      this.currentCalcRule.dependencies = updatedDependencies
      // 重新识别多测次参数
      this.identifyMultiMeasureDeps()
    },
    // 处理计算表达式校验
    handleValidateCalcExpression(expression) {
      // 更新本地规则
      this.currentCalcRule.calculationExpr = expression
      // 执行校验逻辑
      this.validateCalcExpression()
    },
    // 处理计算规则保存
    handleCalcRuleSave(updatedRule) {
      if (this.currentCalcParam) {
        // 直接更新当前参数的计算规则
        this.currentCalcParam.dependencies = updatedRule.dependencies
        this.currentCalcParam.calculationExpr = updatedRule.calculationExpr

        // 触发响应式更新
        this.$forceUpdate()

        this.$message.success('计算规则配置成功')
      } else {
        this.$message.error('保存失败：未找到对应的参数')
      }
    },
    // 校验计算表达式
    validateCalcExpression() {
      const { calculationExpr, dependencies } = this.currentCalcRule

      if (!calculationExpr.trim()) {
        this.validateResult = '请输入计算表达式'
        this.validateSuccess = false
        return
      }

      if (dependencies.length === 0) {
        this.validateResult = '请至少选择一个依赖参数'
        this.validateSuccess = false
        return
      }

      this.validateLoading = true

      try {
        // 获取所有基础参数用于验证
        const allBaseParams = this.getAllBaseParams()

        // 识别多测次依赖参数
        const multiMeasureDeps = allBaseParams.filter(
          (param) =>
            dependencies.includes(param.paramCode) &&
            param.isMultiMeasure &&
            param.multiMeasureCount > 1
        )

        const result = this.formulaCalculator.validateExpression(
          calculationExpr,
          dependencies,
          multiMeasureDeps
        )

        this.validateResult = result.message
        this.validateSuccess = result.valid
      } catch (error) {
        this.validateResult = `验证失败: ${error.message}`
        this.validateSuccess = false
      } finally {
        this.validateLoading = false
      }
    },

    // 保存计算规则配置
    saveCalcRule() {
      if (!this.currentCalcParam) return

      this.currentCalcParam.dependencies = [
        ...this.currentCalcRule.dependencies
      ]
      this.currentCalcParam.calculationExpr =
        this.currentCalcRule.calculationExpr

      Message.success('计算规则配置成功')
      this.calcRuleDialogVisible = false
      this.currentCalcParam = null
      this.currentGroupInfo = {
        groupIndex: -1,
        childIndex: -1,
        isNested: false
      }
    },

    // 预览配置
    previewConfig() {
      this.previewJson = JSON.stringify(this.configForm, null, 2)
      this.previewDialogVisible = true
    },

    // 复制预览JSON
    copyPreviewJson() {
      navigator.clipboard
        .writeText(this.previewJson)
        .then(() => {
          Message.success('JSON已复制到剪贴板')
        })
        .catch(() => {
          Message.error('复制失败，请手动复制')
        })
    },

    // 显示导入配置弹窗
    showImportDialog() {
      // 重置导入表单
      this.importForm = {
        jsonStr: '',
        coverType: 'cover'
      }
      this.importDialogVisible = true
    },

    // 处理导入配置
    handleImportConfig(importData) {
      const { jsonStr, coverType } = importData

      if (!jsonStr.trim()) {
        this.$message.error('请粘贴参数配置JSON')
        return
      }

      try {
        // 解析JSON
        const importConfig = JSON.parse(jsonStr.trim())

        // 校验核心字段
        const requiredFields = [
          'projectId',
          'projectName',
          'standardCode',
          'paramGroups'
        ]
        const missingFields = requiredFields.filter(
          (field) => !importConfig[field]
        )
        if (missingFields.length > 0) {
          this.$message.error(
            `导入失败：缺少核心字段 ${missingFields.join('、')}`
          )
          return
        }

        // 校验参数编码唯一性
        if (!this.validateParamCodesUnique(importConfig)) {
          this.$message.error('导入失败：存在重复的参数编码')
          return
        }

        // 处理导入逻辑
        if (coverType === 'cover') {
          // 覆盖当前配置
          this.configForm = {
            ...importConfig,
            paramGroups: importConfig.paramGroups || []
          }
        } else {
          // 合并配置（新增参数组，保留原有基础信息）
          const newParamGroups = importConfig.paramGroups.filter(
            (newGroup) =>
              !this.configForm.paramGroups.some(
                (existGroup) => existGroup.groupId === newGroup.groupId
              )
          )
          this.configForm.paramGroups = [
            ...this.configForm.paramGroups,
            ...newParamGroups
          ]

          // 合并基础信息（如果导入的信息非空）
          if (importConfig.projectName)
            this.configForm.projectName = importConfig.projectName
          if (importConfig.standardCode)
            this.configForm.standardCode = importConfig.standardCode
          if (!this.configForm.projectId)
            this.configForm.projectId = importConfig.projectId
        }

        this.saveConfigVersion()
        this.$message.success(
          `导入成功！共 ${this.configForm.paramGroups.length} 个参数组`
        )
        this.importDialogVisible = false
      } catch (error) {
        console.error('导入配置解析失败：', error)
        this.$message.error('导入失败：JSON格式错误或配置不符合要求')
      }
    },
    // 校验参数编码唯一性
    validateParamCodesUnique(config) {
      const allParamCodes = new Set()
      let hasDuplicate = false

      const checkParams = (params) => {
        if (!params || !Array.isArray(params)) return
        params.forEach((param) => {
          if (param.paramCode) {
            if (allParamCodes.has(param.paramCode)) {
              hasDuplicate = true
              return
            }
            allParamCodes.add(param.paramCode)
          }
        })
      }

      config.paramGroups.forEach((group) => {
        checkParams(group.paramItems)
        if (group.childGroups) {
          group.childGroups.forEach((childGroup) => {
            checkParams(childGroup.paramItems)
          })
        }
      })

      return !hasDuplicate
    },
    // 显示模板对话框
    showTemplateDialog() {
      this.templateDialogVisible = true
    },

    // 应用模板
    applyTemplate(templateKey) {
      const template = this.templateConfigs[templateKey]
      if (!template) return

      MessageBox.confirm(
        `确定要应用"${template.projectName}"模板吗？当前配置将被覆盖。`,
        '应用模板',
        {
          type: 'warning',
          confirmButtonText: '确定应用',
          cancelButtonText: '取消'
        }
      )
        .then(() => {
          this.configForm.projectName = template.projectName
          this.configForm.standardCode = template.standardCode
          this.configForm.description = template.description

          // 转换模板结构
          this.configForm.paramGroups = template.paramGroups.map(
            (group, index) => ({
              groupId: `GRP${generateId(6)}_${index}`,
              groupName: group.groupName,
              isNested: group.isNested || false,
              allowDynamicRows: group.allowDynamicRows || false,
              maxRows: group.maxRows || 3,
              sortOrder: group.sortOrder || index + 1,
              childGroups: group.childGroups
                ? group.childGroups.map((child, childIndex) => ({
                    groupId: `CHILD${generateId(4)}_${childIndex}`,
                    groupName: child.groupName,
                    paramItems: this.initParamItems(child.paramItems)
                  }))
                : [],
              paramItems: group.paramItems
                ? this.initParamItems(group.paramItems)
                : []
            })
          )

          this.saveConfigVersion()
          Message.success(`已应用"${template.name}"模板`)
          this.templateDialogVisible = false
        })
        .catch(() => {})
    },

    // 初始化参数项
    initParamItems(items) {
      return items.map((item) => ({
        paramId: `PARAM${generateId(8)}`,
        ...item,
        required: item.required || false,
        precision: item.precision || 1,
        columnWidth: item.columnWidth || 120,
        isMultiMeasure: item.isMultiMeasure || false,
        multiMeasureCount: item.multiMeasureCount || 1,
        sortOrder: item.sortOrder || 1
      }))
    },

    // 显示历史对话框
    showHistoryDialog() {
      this.historyDialogVisible = true
    },

    // 保存配置版本
    saveConfigVersion() {
      const version = {
        version: this.currentVersion + 1,
        timestamp: new Date().toISOString(),
        config: deepClone(this.configForm),
        description: `版本 ${this.currentVersion + 1}`
      }

      this.configHistory.unshift(version)
      this.currentVersion++

      // 只保留最近10个版本
      if (this.configHistory.length > 10) {
        this.configHistory = this.configHistory.slice(0, 10)
      }

      // 保存到本地存储
      localStorage.setItem('configHistory', JSON.stringify(this.configHistory))
    },

    // 恢复历史版本
    restoreConfigVersion(versionIndex) {
      MessageBox.confirm('恢复此版本将覆盖当前配置，是否继续？', '恢复版本', {
        type: 'warning',
        confirmButtonText: '确定恢复',
        cancelButtonText: '取消'
      })
        .then(() => {
          const version = this.configHistory[versionIndex]
          this.configForm = deepClone(version.config)
          this.currentVersion = version.version
          Message.success(`已恢复版本 ${version.version}`)
          this.historyDialogVisible = false
        })
        .catch(() => {})
    },

    // 校验配置完整性
    validateConfig() {
      const errors = this.formulaCalculator.validateConfig(this.configForm)

      if (errors.length === 0) {
        Message.success('配置校验通过！')
      } else {
        const errorMsg = errors.slice(0, 5).join('\n')
        MessageBox.alert(
          `发现 ${errors.length} 个问题：\n\n${errorMsg}${
            errors.length > 5 ? '\n\n... 还有更多问题' : ''
          }`,
          '配置校验失败',
          {
            type: 'error',
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false
          }
        )
      }
    },

    // 保存配置
    saveConfig() {
      // 表单验证
      if (!this.configForm.projectName.trim()) {
        Message.error('请填写检测项目名称')
        return
      }
      if (!this.configForm.projectId.trim()) {
        Message.error('请填写项目编码')
        return
      }
      if (this.configForm.paramGroups.length === 0) {
        Message.error('至少添加一个参数组')
        return
      }

      // 配置校验
      const errors = this.formulaCalculator.validateConfig(this.configForm)
      if (errors.length > 0) {
        MessageBox.confirm(
          `发现 ${errors.length} 个配置问题，是否继续保存？\n\n${errors
            .slice(0, 3)
            .join('\n')}${errors.length > 3 ? '\n...' : ''}`,
          '配置存在问题',
          {
            type: 'warning',
            confirmButtonText: '继续保存',
            cancelButtonText: '取消'
          }
        )
          .then(() => {
            this.doSaveConfig()
          })
          .catch(() => {})
        return
      }

      this.doSaveConfig()
    },

    // 执行保存配置
    doSaveConfig() {
      this.saving = true

      // 模拟API调用
      setTimeout(() => {
        // 实际项目中替换为真实的API调用
        localStorage.setItem('detectionConfig', JSON.stringify(this.configForm))

        this.saveConfigVersion()
        Message.success('参数配置保存成功！')
        this.saving = false

        // 可以跳转到其他页面
        // this.$router.push({ path: '/test-list' });
      }, 1000)
    },
     /**
     * 显示参数对照表弹框
     */
    showParamMappingDialog() {
      var _this = this
      _this.mappingDialogVisible = true
      // 配置校验
      const errors = this.formulaCalculator.validateConfig(this.configForm)
      _this.mappingJson = _this.configForm

      if (errors.length > 0) {
        MessageBox.confirm(
          `发现 ${errors.length} 个配置问题，是否继续操作？\n\n${errors
            .slice(0, 3)
            .join('\n')}${errors.length > 3 ? '\n...' : ''}`,
          '配置存在问题',
          {
            type: 'warning',
            confirmButtonText: '继续查看',
            cancelButtonText: '取消'
          }
        )
          .then(() => {
              // 确保组件已渲染后生成对照表
              _this.$nextTick(() => {
                if (_this.$refs.paramMapping) {
                  _this.$refs.paramMapping.generateMapping()
                }
              })
          })
          .catch(() => {})
        return
      }
      // 确保组件已渲染后生成对照表
      _this.$nextTick(() => {
        if (_this.$refs.paramMapping) {
          _this.$refs.paramMapping.generateMapping()
        }
      })

     
    },

    /**
     * 导出对照表
     */
    handleExportMapping(format) {
      if (this.$refs.paramMapping) {
        this.$refs.paramMapping.exportMapping(format)
      }
    }
  }
}
</script>

<style scoped>
.param-config-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.config-card {
  border-radius: 8px;
  border: 1px solid #e6e8eb;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-btn {
  margin-right: 15px;
  color: #606266;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 基础信息区域 */
.base-info-section {
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.base-info-form {
  margin-top: 15px;
}

/* 参数组配置区域 */
.param-groups-section {
  margin-top: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-actions {
  display: flex;
  gap: 10px;
}

/* 配置统计信息 */
.config-stats {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

/* 参数组卡片样式 */
.param-group-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e6e8eb;
  transition: all 0.3s ease;
}

.param-group-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
  border-color: #c0c4cc;
}

/* 参数组头部 */
.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.group-header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.group-drag-handle {
  color: #c0c4cc;
  cursor: move;
  font-size: 16px;
}

.group-drag-handle:hover {
  color: #409eff;
}

.group-name-input {
  width: 280px;
}

.sort-order-input {
  width: 80px;
}

.group-header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.max-rows-input {
  width: 100px;
}

/* 嵌套组样式 */
.nested-groups {
  padding-left: 25px;
  border-left: 2px dashed #dcdfe6;
  margin-top: 15px;
}

.child-group-card {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e6e8eb;
}

.child-group-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.child-group-drag-handle {
  color: #c0c4cc;
  cursor: move;
}

.child-group-name-input {
  width: 220px;
}

.add-child-group-btn {
  margin-left: 25px;
  color: #409eff;
  font-weight: 500;
}

/* 非嵌套组样式 */
.normal-group-params {
  margin-top: 15px;
}

.normal-group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
}

.param-count {
  font-size: 12px;
  color: #909399;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  color: #c0c4cc;
}

.empty-state p {
  margin-bottom: 20px;
  font-size: 14px;
}

/* 全局加载样式 */
.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.loading-content i {
  font-size: 32px;
  color: #409eff;
  margin-bottom: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .param-config-page {
    padding: 15px;
  }

  .group-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .group-header-actions {
    width: 100%;
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .section-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .nested-groups {
    padding-left: 15px;
  }
}

/* 动画效果 */
.param-group-card {
  animation: fadeInUp 0.5s ease;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 拖拽样式 */
.sortable-ghost {
  opacity: 0.5;
  background: #f0f9ff;
}

.sortable-chosen {
  background: #f0f9ff;
  border-color: #409eff;
}
</style>
